/**
 * 
 */
package wineshop.utils;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * @author Administrator
 *
 */
public class AuthenticationFilter implements Filter {

	/* (non-Javadoc)
	 * @see javax.servlet.Filter#destroy()
	 */
	
	public void destroy() {
		System.out.println("AuthenticationFilter is destoried now!");

	}

	/* (non-Javadoc)
	 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
	 */
	
	public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException {
		System.out.println("AuthenticationFilter is doFilter!");
		
		HttpServletRequest hreq=(HttpServletRequest)request;
		HttpServletResponse hrep=(HttpServletResponse)response;

		String fileName = hreq.getRequestURI().substring(hreq.getRequestURI().lastIndexOf("/") + 1);
		
		if (fileName.indexOf(".gif") != -1 
				|| fileName.indexOf(".jpg") != -1
				|| fileName.indexOf(".css") != -1
				|| fileName.indexOf("wineshopMgr") != -1){
			System.out.println(fileName+"是普通资源，放行!");
			chain.doFilter(request, response);
		} 
		else {
			if (hreq.getSession().getAttribute("loginedMgr") == null){
				System.out.println(fileName+"是受限资源，没有登录，需先登录!");
				hrep.sendRedirect(SysUtils.getSrvPath(hreq)+ "/SecurityMgr?act=toLogin");
			}
			else{
				System.out.println(fileName+"是受限资源，已登录，放行!");
				chain.doFilter(request, response);
			}
		}
	}

	/* (non-Javadoc)
	 * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
	 */
	
	public void init(FilterConfig arg0) throws ServletException {
		System.out.println("AuthenticationFilter is init ok now!");

	}

}
